<template>
  <view class="add-education-container">
    <!-- 页头 -->
    <view class="header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <image
            class="back-icon"
            src="/static/icons/candidate/pre_page.png"
          ></image>
        </view>
        <text class="header-title">{{
          isEdit ? "编辑教育经历" : "添加教育经历"
        }}</text>
        <view class="save-btn" @click="saveEducation">
          <text class="save-text">保存</text>
        </view>
      </view>
    </view>

    <!-- 表单内容 -->
    <view class="form-content">
      <view class="card-box">
        <!-- 学校名称 -->
        <view class="block-name">
          <text class="field-lable-words">学校名称</text>
          <view class="field-wrapper" @click="goToSchoolInput">
            <text
              class="education-input"
              :class="{ placeholder: !formData.school }"
            >
              {{ formData.school || "请输入" }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
            ></image>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 学历 -->
        <view class="block-name">
          <text class="field-lable-words">学历</text>
          <view class="field-wrapper" @click="goToEducationSelect">
            <text
              class="education-input"
              :class="{ placeholder: !formData.education }"
            >
              {{ formData.education || "请选择" }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
            ></image>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 专业 -->
        <view class="block-name">
          <text class="field-lable-words">专业</text>
          <view class="field-wrapper" @click="goToMajorInput">
            <text
              class="education-input"
              :class="{ placeholder: !formData.major }"
            >
              {{ formData.major || "请输入" }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
            ></image>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 在校时间 -->
        <view class="block-name">
          <text class="field-lable-words">在校时间</text>
          <view class="education-day-wrapper">
            <!-- 开始时间 -->
            <view class="time-picker-item">
              <picker
                mode="multiSelector"
                :range="beginDateRange"
                :value="beginDateIndex"
                @change="onBeginDateChange"
                :class="!formData.beginDate ? 'picker' : 'picker-words'"
              >
                <view class="field-words">{{
                  getDisplayBeginDate() || "请选择入学时间"
                }}</view>
              </picker>
            </view>

            <view class="day-split">
              <text class="split-text">至</text>
            </view>

            <!-- 结束时间 -->
            <view class="time-picker-item">
              <picker
                mode="multiSelector"
                :range="endDateRange"
                :value="endDateIndex"
                @change="onEndDateChange"
                :class="!formData.endDate ? 'picker' : 'picker-words'"
              >
                <view class="field-words">{{
                  getDisplayEndDate() || "请选择毕业时间"
                }}</view>
              </picker>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 删除按钮（仅在编辑模式下显示） -->
    <view v-if="isEdit" class="delete-section">
      <view class="delete-btn" @click="showDeleteConfirm">
        <text class="delete-text">删除教育经历</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import {
  submitEducation,
  deleteEducation,
  getEducationDetail,
} from "../../../api/resume.js";

// 表单数据
const formData = ref({
  id: "", // 教育经历ID（编辑时需要）
  school: "",
  education: "",
  major: "",
  beginDate: "",
  endDate: "",
});

// 简历ID
const resumeId = ref("");
// 是否为编辑模式
const isEdit = ref(false);
// 教育经历ID
const educationId = ref("");

// 学历选项
const educationOptions = [
  "高中",
  "中专",
  "大专",
  "本科",
  "硕士",
  "博士",
  "博士后",
];

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 保存教育经历
const saveEducation = async () => {
  console.log("保存教育经历:", formData.value);

  // 表单验证
  if (!formData.value.school) {
    uni.showToast({
      title: "请输入学校名称",
      icon: "none",
    });
    return;
  }

  if (!formData.value.education) {
    uni.showToast({
      title: "请选择学历",
      icon: "none",
    });
    return;
  }

  if (!formData.value.major) {
    uni.showToast({
      title: "请输入专业",
      icon: "none",
    });
    return;
  }

  if (!formData.value.beginDate) {
    uni.showToast({
      title: "请选择开始时间",
      icon: "none",
    });
    return;
  }

  if (!formData.value.endDate) {
    uni.showToast({
      title: "请选择结束时间",
      icon: "none",
    });
    return;
  }

  // 构建提交数据
  const submitData = {
    resumeId: resumeId.value,
    school: formData.value.school,
    education: formData.value.education,
    major: formData.value.major,
    beginDate: formData.value.beginDate,
    endDate: formData.value.endDate,
  };

  // 如果是编辑模式，添加ID
  if (isEdit.value && educationId.value) {
    submitData.id = educationId.value;
  }

  console.log("提交数据:", submitData);

  try {
    // 调用接口保存
    await submitEducation(submitData);

    // 显示成功提示
    uni.showToast({
      title: isEdit.value ? "更新成功" : "保存成功",
      icon: "success",
    });

    // 延迟跳转回简历页面，确保用户看到成功提示
    setTimeout(() => {
      uni.reLaunch({
        url: "/pages/candidate/resume/resume",
      });
    }, 1500);
  } catch (error) {
    console.log("保存失败:", error);
    uni.showToast({
      title: "保存失败，请重试",
      icon: "none",
    });
  }
};

// 显示删除确认对话框
const showDeleteConfirm = () => {
  uni.showModal({
    title: "确认删除",
    content: "确定要删除这条教育经历吗？删除后无法恢复。",
    confirmText: "删除",
    confirmColor: "#ff4757",
    cancelText: "取消",
    success: (res) => {
      if (res.confirm) {
        deleteEducationExp();
      }
    },
  });
};

// 删除教育经历
const deleteEducationExp = async () => {
  if (!educationId.value) {
    uni.showToast({
      title: "无法删除，缺少教育经历ID",
      icon: "none",
    });
    return;
  }

  try {
    await deleteEducation(educationId.value);
    console.log("删除成功");

    uni.showToast({
      title: "删除成功",
      icon: "success",
    });

    // 延迟跳转回简历页面
    setTimeout(() => {
      uni.reLaunch({
        url: "/pages/candidate/resume/resume",
      });
    }, 1500);
  } catch (error) {
    console.log("删除失败:", error);
    uni.showToast({
      title: "删除失败，请重试",
      icon: "none",
    });
  }
};

// 跳转到学校名称输入页面
const goToSchoolInput = () => {
  uni.navigateTo({
    url: `/pages/candidate/resume/commonInput?type=school&value=${encodeURIComponent(
      formData.value.school || ""
    )}`,
  });
};

// 跳转到学历选择页面
const goToEducationSelect = () => {
  uni.showActionSheet({
    itemList: educationOptions,
    success: (res) => {
      const selectedIndex = res.tapIndex;
      formData.value.education = educationOptions[selectedIndex];
    },
  });
};

// 跳转到专业输入页面
const goToMajorInput = () => {
  uni.navigateTo({
    url: `/pages/candidate/resume/commonInput?type=major&value=${encodeURIComponent(
      formData.value.major || ""
    )}`,
  });
};

// 获取显示的时间段文本
const getDisplayDateRange = () => {
  if (!formData.value.beginDate || !formData.value.endDate) {
    return "";
  }

  const beginDate = formData.value.beginDate;
  const endDate = formData.value.endDate;

  if (beginDate === "1990之前") {
    return `${beginDate} - ${endDate}`;
  }

  // 格式化显示：2023年9月 - 2033年9月
  const formatDate = (dateStr) => {
    if (!dateStr || dateStr === "至今") return dateStr;

    const [year, month] = dateStr.split("-");
    if (year && month) {
      return `${year}年${parseInt(month)}月`;
    }
    return dateStr;
  };

  return `${formatDate(beginDate)} - ${formatDate(endDate)}`;
};

// 日期选择器相关
const beginDateRange = ref([]);
const endDateRange = ref([]);
const beginDateIndex = ref([0, 0]);
const endDateIndex = ref([0, 0]);

// 生成开始时间选择器数据
const generateBeginDateRange = () => {
  const currentYear = new Date().getFullYear();
  const years = [];
  const months = [];

  // 生成年份：从今年到1990年（倒序）
  for (let year = currentYear; year >= 1990; year--) {
    years.push(year + "年");
  }

  // 添加"1990之前"选项
  years.push("1990之前");

  // 生成月份：1月到12月
  for (let month = 1; month <= 12; month++) {
    months.push(month + "月");
  }

  return [years, months];
};

// 生成结束时间选择器数据（基于开始时间）
const generateEndDateRange = (beginYear) => {
  const years = [];
  const months = [];

  if (beginYear === "1990之前") {
    // 1990之前的情况
    years.push("1990");
  } else {
    // 从开始年份到开始年份+10年
    const startYear = parseInt(beginYear);
    for (let year = startYear; year <= startYear + 10; year++) {
      years.push(year + "年");
    }
  }

  // 生成月份：1月到12月
  for (let month = 1; month <= 12; month++) {
    months.push(month + "月");
  }

  return [years, months];
};

// 初始化开始时间范围
beginDateRange.value = generateBeginDateRange();

// 开始时间变化处理
const onBeginDateChange = (e) => {
  const [yearIndex, monthIndex] = e.detail.value;
  beginDateIndex.value = [yearIndex, monthIndex];

  const yearText = beginDateRange.value[0][yearIndex];

  if (yearText === "1990之前") {
    formData.value.beginDate = "1990之前";
  } else {
    const year = yearText.replace("年", "");
    const month = beginDateRange.value[1][monthIndex].replace("月", "");
    formData.value.beginDate = `${year}-${month.padStart(2, "0")}`;
  }

  // 重新生成结束时间范围
  endDateRange.value = generateEndDateRange(formData.value.beginDate);
  endDateIndex.value = [0, 0];
  formData.value.endDate = "";

  console.log("设置开始时间:", formData.value.beginDate);
};

// 结束时间变化处理
const onEndDateChange = (e) => {
  const [yearIndex, monthIndex] = e.detail.value;
  endDateIndex.value = [yearIndex, monthIndex];

  const yearText = endDateRange.value[0][yearIndex];
  const month = endDateRange.value[1][monthIndex].replace("月", "");

  if (yearText === "1990") {
    formData.value.endDate = "1990";
  } else {
    const year = yearText.replace("年", "");
    formData.value.endDate = `${year}-${month.padStart(2, "0")}`;
  }

  console.log("设置结束时间:", formData.value.endDate);
};

// 获取显示的开始时间文本
const getDisplayBeginDate = () => {
  if (!formData.value.beginDate) return "";

  if (formData.value.beginDate === "1990之前") {
    return "1990之前";
  }

  const [year, month] = formData.value.beginDate.split("-");
  if (year && month) {
    return `${year}年${parseInt(month)}月`;
  }
  return formData.value.beginDate;
};

// 获取显示的结束时间文本
const getDisplayEndDate = () => {
  if (!formData.value.endDate) return "";

  if (formData.value.endDate === "1990") {
    return "1990";
  }

  const [year, month] = formData.value.endDate.split("-");
  if (year && month) {
    return `${year}年${parseInt(month)}月`;
  }
  return formData.value.endDate;
};

// 更新字段值（从子页面返回时调用）
const updateFieldValue = (field, value) => {
  if (formData.value.hasOwnProperty(field)) {
    formData.value[field] = value;
  }
};

// 页面显示时处理返回数据
const onShow = () => {
  // 这个方法会在页面显示时调用，包括从其他页面返回时
  // 由于数据已经通过 updateFieldValue 方法更新，这里不需要额外处理
  // 但保留这个方法以确保页面生命周期的完整性
};

// 暴露方法给子页面调用
defineExpose({
  updateFieldValue,
  onShow,
});

// 页面加载时设置事件监听器
onMounted(() => {
  // 获取页面参数中的简历ID
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options || {};

  if (options.resumeId) {
    resumeId.value = decodeURIComponent(options.resumeId);
    console.log("获取到简历ID:", resumeId.value);
  }

  // 获取教育经历ID（编辑模式）
  if (options.id) {
    isEdit.value = true;
    educationId.value = decodeURIComponent(options.id);
    console.log("获取到教育经历ID:", educationId.value);

    // 调用接口获取详情
    uni.showLoading({
      title: "加载中",
    });
    getEducationDetail(educationId.value)
      .then((response) => {
        uni.hideLoading();
        if (response) {
          // 映射字段名称
          formData.value = {
            id: response.id || "",
            school: response.school || "",
            education: response.education || "",
            major: response.major || "",
            beginDate: response.beginDate || "",
            endDate: response.endDate || "",
          };

          // 安全地解析日期字符串
          try {
            // 处理开始时间
            if (
              formData.value.beginDate &&
              formData.value.beginDate !== "1990之前"
            ) {
              // 检查日期格式是否为 YYYY-MM 或 YYYY-MM-DD
              if (formData.value.beginDate.includes("-")) {
                const [year, month] = formData.value.beginDate.split("-");
                if (year && month && !isNaN(year) && !isNaN(month)) {
                  // 如果是 YYYY-MM 格式，添加日期部分
                  const dateStr =
                    formData.value.beginDate.length === 7
                      ? formData.value.beginDate + "-01"
                      : formData.value.beginDate;
                  const beginDate = new Date(dateStr);
                  if (!isNaN(beginDate.getTime())) {
                    formData.value.beginDate = beginDate
                      .toISOString()
                      .slice(0, 10);
                  }
                }
              }
            }

            // 处理结束时间
            if (formData.value.endDate && formData.value.endDate !== "至今") {
              // 检查日期格式是否为 YYYY-MM 或 YYYY-MM-DD
              if (formData.value.endDate.includes("-")) {
                const [year, month] = formData.value.endDate.split("-");
                if (year && month && !isNaN(year) && !isNaN(month)) {
                  // 如果是 YYYY-MM 格式，添加日期部分
                  const dateStr =
                    formData.value.endDate.length === 7
                      ? formData.value.endDate + "-01"
                      : formData.value.endDate;
                  const endDate = new Date(dateStr);
                  if (!isNaN(endDate.getTime())) {
                    formData.value.endDate = endDate.toISOString().slice(0, 10);
                  }
                }
              }
            }
          } catch (dateError) {
            console.warn("日期解析失败，使用原始值:", dateError);
          }

          // 设置日期选择器
          try {
            if (formData.value.beginDate) {
              // 设置开始时间选择器
              if (formData.value.beginDate === "1990之前") {
                beginDateIndex.value = [beginDateRange.value[0].length - 1, 0]; // 1990之前的索引
              } else {
                const [year, month] = formData.value.beginDate.split("-");
                if (year && month) {
                  const yearIndex = beginDateRange.value[0].findIndex((item) =>
                    item.includes(year)
                  );
                  const monthIndex = beginDateRange.value[1].findIndex((item) =>
                    item.includes(month)
                  );
                  if (yearIndex >= 0 && monthIndex >= 0) {
                    beginDateIndex.value = [yearIndex, monthIndex];
                  }
                }
              }

              // 重新生成结束时间范围并设置结束时间选择器
              endDateRange.value = generateEndDateRange(
                formData.value.beginDate
              );

              if (formData.value.endDate) {
                if (formData.value.endDate === "1990") {
                  endDateIndex.value = [0, 0]; // 1990的索引
                } else {
                  const [year, month] = formData.value.endDate.split("-");
                  if (year && month) {
                    const yearIndex = endDateRange.value[0].findIndex((item) =>
                      item.includes(year)
                    );
                    const monthIndex = endDateRange.value[1].findIndex((item) =>
                      item.includes(month)
                    );
                    if (yearIndex >= 0 && monthIndex >= 0) {
                      endDateIndex.value = [yearIndex, monthIndex];
                    }
                  }
                }
              }
            }
          } catch (error) {
            console.warn("设置日期选择器失败:", error);
          }
        } else {
          uni.hideLoading();
          uni.showToast({
            title: "加载教育经历失败",
            icon: "none",
          });
        }
      })
      .catch((error) => {
        uni.hideLoading();
        console.log("加载教育经历失败:", error);
        uni.showToast({
          title: "加载教育经历失败，请重试",
          icon: "none",
        });
      });
  }

  // 监听学校名称更新事件
  uni.$on("updateSchool", (value) => {
    formData.value.school = value;
  });

  // 监听专业更新事件
  uni.$on("updateMajor", (value) => {
    formData.value.major = value;
  });

  // 调用 onShow 方法以确保数据正确初始化
  onShow();
});

// 页面卸载时移除事件监听器
onUnmounted(() => {
  uni.$off("updateSchool");
  uni.$off("updateMajor");
});
</script>

<style scoped lang="less">
.add-education-container {
  background-color: #fff;
  min-height: 100vh;
}

/* 页头样式 */
.header {
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif;
}

.save-btn {
  min-width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 10rpx;
}

.save-text {
  font-size: 32rpx;
  color: #333;
  font-weight: 400;
}

/* 表单内容样式 */
.form-content {
  background-color: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;
}

/* 卡片样式 */
.card-box {
  background-color: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;
}

/* 字段块样式 */
.block-name {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 40rpx 30rpx;
  position: relative;
}

.field-lable-words {
  font-size: 28rpx;
  color: #a6a6a6;
  font-weight: 400;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif;
  margin-bottom: 20rpx;
}

.field-wrapper {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.education-input {
  font-size: 32rpx;
  color: #333;
  font-weight: 400;
  flex: 1;
  text-align: left;
  margin-right: 20rpx;
}

.placeholder {
  color: #999;
}

.right-arrow {
  width: 32rpx;
  height: 32rpx;
  opacity: 0.6;
  flex-shrink: 0;
}

/* 分割线样式 */
.line-wrapper {
  margin: 0 30rpx;
}

.line {
  height: 1px;
  background-color: #f0f0f0;
  width: 100%;
}

/* 时间选择器样式 */
.education-day-wrapper {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.time-picker-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.time-label {
  font-size: 24rpx;
  color: #666;
  text-align: center;
}

.day-split {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 10rpx;
}

.split-text {
  font-size: 28rpx;
  color: #999;
}

.picker {
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
}

.picker-words {
  background-color: transparent;
  padding: 10rpx 20rpx;
  border: none;
}

.field-words {
  font-size: 28rpx;
  color: #333;
  font-weight: 400;
  text-align: center;
}

/* 删除按钮样式 */
.delete-section {
  padding: 20rpx 30rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-btn {
  background-color: #ff6f57;
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  padding: 15rpx 30rpx;
  border-radius: 8rpx;
  text-align: center;
}

.delete-text {
  color: #fff;
}
</style>
